<template>
  <div class="app-container">
    <!-- 查询表单 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true">
      <el-form-item label="电表编号" prop="dbbh">
        <el-input
          v-model="queryParams.dbbh"
          placeholder="请输入电表编号"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="租户" prop="qymc">
        <el-input
          v-model="queryParams.qymc"
          placeholder="请输入租户"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- Tab 栏 -->
    <el-tabs v-model="activeTab" @tab-click="handleTabChange">
      <el-tab-pane label="租用中" name="used"></el-tab-pane>
      <el-tab-pane label="已退用" name="free"></el-tab-pane>
    </el-tabs>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="tableData">
      <el-table-column prop="dbbh" label="电表编号" align="center" />
      <el-table-column prop="zt" label="载体" align="center" />
      <el-table-column prop="fjh" label="房间号" align="center" />
      <el-table-column
        prop="qymc"
        label="租户"
        align="center"
        width="350"
        show-overflow-tooltip
      />

      <el-table-column prop="dbyt" label="电表用途" align="center" />
      <el-table-column prop="qysj" label="启用时间" align="center" />
      <el-table-column prop="csdl" label="初始电量" align="center" />
      <el-table-column prop="dbbl" label="电表倍率" align="center" />
      <el-table-column
        v-if="activeTab === 'free'"
        prop="tysj"
        label="退用时间"
        align="center"
      />
      <el-table-column
        v-if="activeTab === 'free'"
        prop="zzdl"
        label="最终电量"
        align="center"
      />
      <el-table-column
        v-if="activeTab === 'used'"
        label="操作"
        align="center"
        width="180"
      >
        <template #default="scope">
          <el-button type="primary" size="small" @click="openEditEnableDialog(scope.row)">
            修改启用日期及用途
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 修改启用日期及用途弹窗 -->
    <el-dialog
      title="修改启用日期及用途"
      v-model="editEnableDialogVisible"
      width="500px"
      append-to-body
      @close="resetEditEnableForm"
    >
      <el-form :model="editEnableForm" label-width="100px">
        <el-form-item label="用途" prop="dbyt">
          <el-select v-model="editEnableForm.dbyt" placeholder="请选择用途">
            <el-option
              v-for="item in purposeList"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="启用日期" prop="qysj">
          <el-date-picker
            v-model="editEnableForm.qysj"
            type="date"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            placeholder="请选择启用日期"
            style="width: 100%"
            @change="handleEnableDateChange"
          />
        </el-form-item>
        <el-form-item label="初始电量" prop="csdl">
          <el-input
            v-model="editEnableForm.csdl"
            type="number"
            :disabled="true"
            placeholder="自动获取"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editEnableDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEditEnable">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, toRefs } from "vue";
import { selectUseList, selectFreeList, updateEnableInfo, startDayPower } from "@/api/carrier/ammeter";

const activeTab = ref("used");
const tableData = ref([]);
const loading = ref(false);
const total = ref(0);

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    dbbh: undefined,
    qymc: undefined,
  },
});
const { queryParams } = toRefs(data);

// 用途列表
const purposeList = ref(["租用", "自用", "公用"]);

// 编辑弹窗相关
const editEnableDialogVisible = ref(false);
const editEnableForm = reactive({
  dbbh: "",
  dbyt: "",
  qysj: "",
  csdl: "",
});

function openEditEnableDialog(row) {
  console.log('open')
  editEnableForm.dbbh = row.dbbh;
  editEnableForm.dbyt = row.dbyt;
  editEnableForm.qysj = row.qysj;
  editEnableForm.csdl = row.csdl;
  editEnableDialogVisible.value = true;
}

/** 启用日期选择时调用接口获取初始电量 */
function handleEnableDateChange(date) {
  if (!date || !editEnableForm.dbbh) return;

  startDayPower({ dbbh: editEnableForm.dbbh, qysj: date }).then((response) => {
    if (response.code === 200 && response.data.length > 0) {
      editEnableForm.csdl = response.data[0].dbz; // 将返回的电表值赋值给初始电量
    } else {
      editEnableForm.csdl = 0; // 如果接口未返回数据，设置为默认值
    }
  });
}

function submitEditEnable() {
  if (
    !editEnableForm.dbbh ||
    !editEnableForm.dbyt ||
    !editEnableForm.qysj ||
    editEnableForm.csdl === ""
  ) {
    return;
  }
  updateEnableInfo({
    dbbh: editEnableForm.dbbh,
    dbyt: editEnableForm.dbyt,
    timestamp: editEnableForm.qysj,
    dbz: editEnableForm.csdl,
  })
    .then((res) => {
      if (res.code === 200) {
        editEnableDialogVisible.value = false;
        getList();
      }
    })
    .catch(() => {
      // 处理错误
    });
}

/** 重置编辑启用表单 */
function resetEditEnableForm() {
  editEnableForm.dbbh = "";
  editEnableForm.dbyt = "租用";
  editEnableForm.qysj = "";
  editEnableForm.csdl = "";
}

/** 查询列表 */
function getList() {
  loading.value = true;
  const api = activeTab.value === "used" ? selectUseList : selectFreeList;
  api(queryParams.value)
    .then((res) => {
      tableData.value = res.data?.list || [];
      total.value = res.data?.total || 0;
      loading.value = false;
    })
    .catch(() => {
      loading.value = false;
    });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    dbbh: undefined,
    qymc: undefined,
  };
  getList();
}

/** Tab 切换 */
function handleTabChange(tab) {
  activeTab.value = tab.props.name;
  queryParams.value.pageNum = 1;
  getList();
}

getList();
</script>

<style scoped>
.app-container {
  padding: 20px;
}
</style>
